//
//  UIViewController+TFCore.m
//  TFFoundation
//
//  Created by TFAppleWork-Summer on 2017/3/9.
//  Copyright © 2017年 TFAppleWork-Summer. All rights reserved.
//

#import "UIViewController+TFCore.h"
#import "NSObject+TFCore.h"
#import "UIImage+TFCore.h"
#import "TFDefine.h"
#import "UIView+TFCore.h"
#import "NSString+TFCore.h"
#import "TFWebViewController.h"

NSString * const kTFOpenURLJumpStyleKey = @"TFOpenURLJumpStyle";

NSString * const kTFOpenURLStoryboardNameKey = @"TFOpenURLStoryboardName";

NSString * const kTFOpenURLTypeKey = @"TFOpenURLType";

NSString * const kTFOpenURLJumpStylePushIndexKey = @"TFOpenURLJumpStylePushIndex";

NSString * const kTFOpenURLJumpAnimatedKey = @"TFOpenURLJumpAnimated";

NSString * const kTFOpenURLPresentCompletionBlockKey = @"TFOpenURLPresentCompletionBlock";

NSString * const kTFOpenURLViewControllerInitBlockKey = @"TFOpenURLViewControllerInitBlock";

NSString * const kTFOpenURLViewControllerTitleKey = @"TFOpenURLViewControllerTitle";

NSString * const kTFViewControllerViewWillDisappearNotification = @"TFViewControllerViewWillDisappear";

NSString * const kTFViewControllerViewWillAppearNotification = @"TFViewControllerViewWillAppear";

NSString * const kTFViewControllerViewDidLoadNotification = @"TFViewControllerViewDidLoad";

NSString * const kTFViewControllerViewDidDisappearNotification = @"TFViewControllerViewDidDisappear";

NSString * const kTFViewControllerViewDidAppearNotification = @"TFViewControllerViewDidAppear";

UIViewController * TFOpenURL(NSString *url,NSDictionary *params) {
    TFOpenURLType urlType = TFOpenURLTypeViewControllerURL;
    NSNumber *urlTypeValue = [params objectForKey:kTFOpenURLTypeKey];
    if (urlTypeValue) {
        urlType = [urlTypeValue unsignedIntegerValue];
    }
    else {
        if ([url tf_isWebUrl]) {
            urlType = TFOpenURLTypeWebURL;
        }
    }
    switch (urlType) {
        case TFOpenURLTypeViewControllerURL:
        {
            //获取跳转的vc
            Class vcClass = vcClass = NSClassFromString(url);
            return TFOpenVCClass(vcClass,params);
        }
            break;
        case TFOpenURLTypeAppURL: {
            NSURL *appUrl = [NSURL URLWithString:url];
            if ([[UIApplication sharedApplication] canOpenURL:appUrl]) {
                [[UIApplication sharedApplication] openURL:appUrl];
            }
            else {
                TFLog(@"the url you want to open is not right.");
            }
            return nil;
        }
            break;
        case TFOpenURLTypeWebURL: {
            TFOpenURLViewControllerInitBlock webVCInitBlock = ^() {
                TFWebViewController *webVC = [[TFWebViewController alloc] init];
                webVC.url = [NSURL URLWithString:url];
                return webVC;
            };
            NSMutableDictionary *paramsDic = [NSMutableDictionary dictionaryWithDictionary:params];
            [paramsDic setObject:webVCInitBlock forKey:kTFOpenURLViewControllerInitBlockKey];
            return TFOpenVCClass([TFWebViewController class],paramsDic);
        }
            break;
        default:
            break;
    }
};


UIViewController * TFOpenVCClass(Class vcClass,NSDictionary *params) {
    
    UIViewController *currentVC = [[UIApplication sharedApplication].delegate.window.rootViewController tf_visibleViewController];
    UIViewController *jumpVC = nil;
    TFOpenURLViewControllerInitBlock initBlock = params[kTFOpenURLViewControllerInitBlockKey];
    if (initBlock) {
        jumpVC = initBlock();
    }
    else {
        NSString *storyboardName = params[kTFOpenURLStoryboardNameKey];
        if (storyboardName) {
            NSString *identifier = NSStringFromClass(vcClass);
            jumpVC = [[UIStoryboard storyboardWithName:storyboardName bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:identifier];
        }
        else {
            jumpVC = [[vcClass alloc] init];
        }
    }
    NSString *title = params[kTFOpenURLViewControllerTitleKey];
    if (title) {
        jumpVC.title = title;
    }
    jumpVC.params = [NSMutableDictionary dictionaryWithDictionary:params];
    
    TFOpenURLJumpStyle jumpStyle = TFOpenURLJumpStylePush;
    NSNumber *jumpStyleValue = [params objectForKey:kTFOpenURLJumpStyleKey];
    if (jumpStyleValue) {
        jumpStyle = [jumpStyleValue unsignedIntegerValue];
    }
    BOOL animated = YES;
    NSNumber *animatedValue = [params objectForKey:kTFOpenURLJumpAnimatedKey];
    if (animatedValue) {
        animated = [animatedValue boolValue];
    }
    jumpVC.hidesBottomBarWhenPushed = YES;
    switch (jumpStyle) {
        case TFOpenURLJumpStylePush:
        {
            //获取index
            NSInteger index = 0;
            NSNumber *indexValue = params[kTFOpenURLJumpStylePushIndexKey];
            if (indexValue) {
                index = [indexValue integerValue];
            }
            if (index>=0) {
                [currentVC.navigationController pushViewController:jumpVC animated:animated];
            }
            else {
                NSMutableArray *vcsArray = [NSMutableArray arrayWithArray:currentVC.navigationController.viewControllers];
                NSInteger removeLength = ABS(index);
                if (removeLength>=vcsArray.count) {
                    [currentVC.navigationController popToRootViewControllerAnimated:animated];
                }
                else {
                    //移除多余的vc
                    [vcsArray removeObjectsInRange:NSMakeRange(vcsArray.count-removeLength, removeLength)];
                    [vcsArray addObject:jumpVC];
                    [currentVC.navigationController setViewControllers:vcsArray animated:animated];
                }
                
            }
        }
            break;
        case TFOpenURLJumpStylePresent: {
            [currentVC presentViewController:jumpVC animated:animated completion:params[kTFOpenURLPresentCompletionBlockKey]];
        }
            break;
        default:
            break;
    }
    return jumpVC;
};

@implementation UIViewController (TFCore)

+ (void)load {
    [super load];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        TFSwizzleMethod([UIViewController class], @selector(viewDidLoad), @selector(tf_viewDidLoad));
        TFSwizzleMethod([UIViewController class], @selector(viewWillAppear:), @selector(tf_viewWillAppear:));
        TFSwizzleMethod([UIViewController class], @selector(viewDidAppear:), @selector(tf_viewDidAppear:));
        TFSwizzleMethod([UIViewController class], @selector(viewWillDisappear:), @selector(tf_viewWillDisappear:));
        TFSwizzleMethod([UIViewController class], @selector(viewDidDisappear:), @selector(tf_viewDidDisappear:));
    });
}

+ (__kindof UIViewController *)tf_viewControllerWithStoryboardName:(NSString *)storyboardName storyboardId:(NSString *)storyboardId {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:[NSBundle mainBundle]];
    return [storyboard instantiateViewControllerWithIdentifier:storyboardId];
}

+ (UIViewController *)tf_viewControllerWithMainStoryboardId:(NSString *)storyboardId {
    return [UIViewController tf_viewControllerWithStoryboardName:@"Main" storyboardId:storyboardId];
}

+ (UIViewController *)tf_viewControllerWithMainStoryboardAndClassNameAsStoryBoardId {
    return [UIViewController tf_viewControllerWithMainStoryboardId:[self tf_classNameString]];
}

- (void)tf_viewDidLoad {
    [[NSNotificationCenter defaultCenter] postNotificationName:kTFViewControllerViewDidLoadNotification object:self];
    [self tf_viewDidLoad];
}

- (void)tf_viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] postNotificationName:kTFViewControllerViewWillAppearNotification object:self];
    [self tf_viewWillAppear:animated];
}

- (void)tf_viewDidAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] postNotificationName:kTFViewControllerViewDidAppearNotification object:self];
    [self tf_viewDidAppear:animated];
}

- (void)tf_viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] postNotificationName:kTFViewControllerViewWillDisappearNotification object:self];
    [self tf_viewWillDisappear:animated];
}

- (void)tf_viewDidDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] postNotificationName:kTFViewControllerViewDidDisappearNotification object:self];
    [self tf_viewDidDisappear:animated];
}

- (UIViewController *)tf_visibleViewController {
    if ([self isKindOfClass:[UINavigationController class]]) {
        return [[((UINavigationController *)self) visibleViewController] tf_visibleViewController];
    }
    else if ([self isKindOfClass:[UITabBarController class]]) {
        return [[((UITabBarController *)self) selectedViewController] tf_visibleViewController];
    }
    else {
        if (self.presentedViewController) {
            return [self.presentedViewController tf_visibleViewController];
        }
        else {
            return self;
        }
    }
}

- (void)setParams:(NSMutableDictionary *)params {
    [self tf_setAssociateValue:params withkey:@selector(params) assoicationPolicy:TFAssociationPolicy_retain_nonatomic];
}

- (NSDictionary *)params {
    return [self tf_getAssociateValueForKey:_cmd];
}

- (void)tf_setNavigationBarFullTranslucent {
    [self.navigationController.navigationBar setBackgroundImage:[UIImage tf_imageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)tf_recoverNavigationBarToNormal {
    [self.navigationController.navigationBar setBackgroundImage:[[UINavigationBar appearance] backgroundImageForBarMetrics:UIBarMetricsDefault] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
}

- (BOOL)tf_shouldPopBack {
    return YES;
}


@end
